import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import VueRouter from "unplugin-vue-router/vite";
import { fileURLToPath, URL } from "node:url";
import eslintPlugin from "vite-plugin-eslint";

// https://vite.dev/config/
export default defineConfig((mode) => {
  const env = loadEnv(mode, process.cwd(), "");
  // console.log('process.env',process.cwd)
  return {
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    plugins: [
      VueRouter({
        // how and what folders to scan for files
        routesFolder: [
          {
            src: "src/pages",
          },
        ],
        // what files should be considered as a pages
        extensions: [".vue"],
        // where to generate the types
        dts: "./typed-router.d.ts",
      }),
      eslintPlugin({
        include: ["src/**/*.js", "src/**/*.vue", "src/*.js", "src/*.vue"],
      }),
      vue({
        template: {
          compilerOptions: {
            isCustomElement: (tag) => tag === "micro-app",
          },
        },
      }),
      AutoImport({
        imports: ["vue"],
        dts: "auto-imports.d.ts", // 自动导入的类型提示文件
        // 自动导入这些API的目录
        dirs: ["./src/**"],
        vueTemplate: true,
      }),
      Components({
        // 自动扫描的目录，默认是 src/components
        dirs: [
          "src/components",
          "../../packages/common-package/src/components",
        ],
        extensions: ["vue", "tsx"], // 支持的文件后缀
        // 是否生成 d.ts 类型声明，提升TS体验
        dts: "components.d.ts",
        // 解析 UI 库组件
        resolvers: [],
        // 允许在模板中直接使用组件
        include: [/\.vue$/, /\.vue\?vue/, /\.tsx$/],
        // 可选：自定义前缀或命名规则
        // prefix: 'My',
      }),
    ],
    // 防止浏览器端报错
    define: {
      "process.env": {},
    },
    server: {
      // port: env.VITE_PORT,
      // host: env.VITE_API_URL,
      hmr: true,
      // headers: {
      //   'Access-Control-Allow-Origin': '*' //记得配置跨域
      // },
      // fs:{
      //   allow: [
      //       searchForWorkspaceRoot(process.cwd(),'../../sub/subapp'),
      //   ]
      // }
      // proxy: {
      //   '/lead': {
      //     target: env.VITE_SUB_APP_API_URL,
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(/^\/lead/, '')
      //   }
      // }
    },
  };
});
